//一些通用方法

package app

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

func IndexOf(arr []string, s string) bool {
	for i := 0; i < len(arr); i++ {
		if arr[i] == s {
			return true
		}
	}
	return false
}

func GetCurDir() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		fmt.Println(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}

func GetFileAbsolutePath(filepath string) (absolutePath string) {
	absolutePath = GetCurDir() + filepath
	return
}

func FileReadAll(filepath string) []byte {
	absolutePath := GetFileAbsolutePath(filepath)
	file, err := os.Open(absolutePath)
	defer file.Close()
	if err != nil {
		fmt.Println(absolutePath, err)
		return nil
	}

	fileBytes, err := ioutil.ReadAll(file)
	if err != nil {
		fmt.Println(absolutePath, err)
		return nil
	}

	return fileBytes
}

func FileReadAllString(filepath string) string {
	flieBytes := FileReadAll(filepath)
	str := string(flieBytes[:])
	return str
}

func FileWrite(filepath string, fileContent []byte) {
	absolutePath := GetFileAbsolutePath(filepath)
	file, err := os.Create(absolutePath)
	defer file.Close()
	if err != nil {
		fmt.Println(absolutePath, err)
		return
	}
	_, writeErr := file.Write(fileContent)
	if writeErr != nil {
		fmt.Println(absolutePath, writeErr)
		return
	}
}

func FileWriteString(filepath string, fileContent string) {
	absolutePath := GetFileAbsolutePath(filepath)
	file, err := os.Create(absolutePath)
	defer file.Close()
	if err != nil {
		fmt.Println(absolutePath, err)
		return
	}
	_, writeErr := file.WriteString(fileContent)
	if writeErr != nil {
		fmt.Println(absolutePath, writeErr)
		return
	}
}
